<?php
/**
 * @name ManagerModel
 * @author ruansheng
 * @desc 管理员
 */
class ManagerModel {

    private $masterCollection = null;

    public function __construct() {
        $this->masterCollection = MongoClientFactory::getExamMongoClient()->selectCollection('manager');
    }

    /**
     * 添加管理员
     * @param $number
     * @param $username
     * @param $password
     * @return bool
     */
    public function addManager($number, $username, $password) {
        $query = array(
            'number' => $number
        );
        $row = $this->masterCollection->findOne($query);
        if($row) {
            return array(false, '该管理员已存在');
        }
        $data = array(
            'number' => $number,
            'name' => $username,
            'password' => sha1($password),
            'time' => new MongoDate(),
            'status' => 0,
        );
        $item = $this->masterCollection->insert($data, array('safe'=>true));
        if($item['ok'] != 1) {
            return array(false, '添加失败');
        }
        return array($data['_id']->{'$id'}, '添加成功');
    }

    /**
     * 管理员登录检测
     * @param $number
     * @param $password
     * @return bool
     */
    public function login($number, $password) {
        $query = array(
            'number' => $number,
            'password' => sha1($password),
        );
        $row = $this->masterCollection->findOne($query);
        if(empty($row)) {
            return array(false, '账号或密码错误');
        }
        return array($row['_id']->{'$id'}, '登录成功');
    }

    /**
     * 获取info
     * @param $_id
     * @return array
     */
    public function getManagerInfo($_id) {
        $query = array(
            '_id' => new MongoId($_id)
        );
        $info = $this->masterCollection->findOne($query);
        return $info;
    }

    /**
     * 保存设置
     * @param $_id
     * @param $password
     * @return bool
     */
    public function saveSetting($_id, $password) {
        $query = array(
            '_id' => new MongoId($_id)
        );
        $row = $this->masterCollection->findOne($query);
        if(empty($row)) {
            return array(false, '账号不存在');
        }
        $data = array(
            'password' => sha1($password),
        );
        $status = $this->masterCollection->update($query, $data);
        if(!$status) {
            return array(false, '更新失败');
        }
        return array(true, '更新成功');
    }
}
